package com.xinghen.security.core.validate.code;

import com.xinghen.common.util.KaptchaUtil;
import com.xinghen.security.core.properties.SecurityProperties;
import com.xinghen.security.core.validate.code.email.DefaultEmailValidateCodeSender;
import com.xinghen.security.core.validate.code.email.EmailValidateCodeSender;
import com.xinghen.security.core.validate.code.image.ImageValidateCodeGenerator;
import com.xinghen.security.core.validate.code.sms.DefaultSmsValidateCodeSender;
import com.xinghen.security.core.validate.code.sms.SmsValidateCodeSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @author xinghen
 * @ClassName: ValidateCodeBeanConfig
 * @Package: com.xinghen.security.core.validate.code
 * @Description 验证码相关的扩展点配置。配置在这里的bean，业务系统都可以通过声明同类型或同名的bean来覆盖安全
 * 模块默认的配置
 * @create 2018-04-18 15:22
 */
@Configuration
public class ValidateCodeBeanConfig {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private RedisConnectionFactory factory;

    /**
     * 默认的RedisTemplate
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(RedisTemplate.class)
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        return template;
    }

    // TODO: redis 迁移到 xinghen-cloud-security-app 项目中
//    /**
//     * 默认的验证码存取器
//     *
//     * @return
//     */
//    @Bean
//    @ConditionalOnMissingBean(ValidateCodeRepository.class)
//    public ValidateCodeRepository validateCodeRepository() {
//        return new RedisValidateCodeRepository(redisTemplate());
//    }

    /**
     * 默认的图片验证码生成器
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(name = "imageValidateCodeGenerator")
    public ValidateCodeGenerator imageValidateCodeGenerator() {
        ImageValidateCodeGenerator generator = new ImageValidateCodeGenerator();
        generator.setSecurityProperties(securityProperties);
        generator.setCaptchaProducer(KaptchaUtil.defaultKaptcha());
        return generator;
    }

    /**
     * 默认的邮箱验证码发送器
     *
     * @return sms code sender
     */
    @Bean
    @ConditionalOnMissingBean(EmailValidateCodeSender.class)
    public EmailValidateCodeSender emailValidateCodeSender() {
        return new DefaultEmailValidateCodeSender();
    }

    /**
     * 短信验证码发送器
     *
     * @return sms code sender
     */
    @Bean
    @ConditionalOnMissingBean(SmsValidateCodeSender.class)
    public SmsValidateCodeSender smsValidateCodeSender() {
        return new DefaultSmsValidateCodeSender();
    }

}
